<template>
<div class="mb-audit-comment">
  <!-- 标题 -->
  <div class="comment-title" :class="{'comment-required': commentOpt.required || commentOpt.needElecseal || commentOpt.needEsignature}">{{commentOpt.label}}</div>
  <!-- 是否同意radio -->
  <van-radio-group v-model="approval">
    <van-row class="comment-approval" gutter="10">
      <van-col v-for="(item, index) in commentOpt.options" :key="index">
        <van-radio :name="item.id">{{item.name}}</van-radio>
      </van-col>
    </van-row>
  </van-radio-group>
  <!-- 意见填写区 -->
  <van-field v-model="comment" type="textarea" class="comment-text" :placeholder="placeholder" :autosize="autosize" show-word-limit :maxlength="maxlength"/>
  <!-- 印章/签名 -->
  <div class="comment-chapter" @click="chapterSelect" v-if="commentOpt.elecseal || commentOpt.esignature" :class="{'comment-chapter-empty': !chapterUrl}">
    <img :src="chapterUrl" class="chapter" v-if="chapterUrl"/>
    <a class="chapter-delete" @click.stop="chapterDelete" v-if="chapterUrl"></a>
  </div>
  <van-popup 
    v-model="chapterPopup" 
    position="bottom"
    get-container="body"
    :style="{ width: '100%',height: '100%' }"
  >
    <van-nav-bar @click-left="chapterPopup = false" class="navbar">
      <van-icon name="cross" size="20" slot="left" />
      <van-tabs v-model="active" slot="title" color="#1989fa" @change="tabChange">
        <van-tab title="印章" name="elecseal" v-if="commentOpt.elecseal"></van-tab>
        <van-tab title="签名" name="esignature" v-if="commentOpt.esignature"></van-tab>
      </van-tabs>
    </van-nav-bar>
    <div class="tabs-content">
      <div class="tab-panel" v-if="commentOpt.elecseal && active === 'elecseal'" :class="{'seal-empty': !seals.length}">
        <div class="seal-box" v-for="(item, index) in seals" :key="index" @click="sealsChange(item)">
          <div class="seal" :class="{'seal-selected': item.checked }">
            <van-icon 
              :name="item.checked ? 'success' : 'circle'" 
              class="seal-icon"
              :class="{'seal-icon-checked': item.checked}"
              size="20px" 
              color="#dddee1"/>
            <img :src="item.url">
          </div>
        </div>
      </div>
      <div class="tab-panel" v-if="commentOpt.esignature && active === 'esignature'">
        <div class="esignatrue-box" v-show="!esignatureEdit">
          <canvas ref="canvas"></canvas>
        </div>
        <div class="esignatrue-img" v-show="esignatureEdit">
          <img :src="esignatureData" style="display: block;">
        </div>
      </div>
      <van-button type="info" block v-if="commentOpt.elecseal && active === 'elecseal'" @click="elecsealConfirm" :disabled="!seals.length">{{confirmText}}</van-button>
      <van-row class="form-add-actions" v-if="commentOpt.esignature && active === 'esignature' && !esignatureEdit" >
        <van-col span="12">
          <van-button block @click="clearCanvas">{{clearText}}</van-button>
        </van-col>
        <van-col span="12">
          <van-button block type="info" @click="canvasConfirm">{{confirmText}}</van-button>
        </van-col>
      </van-row>
       <van-row class="form-add-actions" v-if="commentOpt.esignature && active === 'esignature' && esignatureEdit" >
        <van-col span="12">
          <van-button block @click="editCanvas">{{editText}}</van-button>
        </van-col>
        <van-col span="12">
          <van-button block type="info" @click="useCanvas">{{useText}}</van-button>
        </van-col>
      </van-row>
    </div>  
  </van-popup>
</div>
</template>

<script>
import { request } from 'utils/http'
import { serialize } from 'utils'
import SignaturePad from "./signature"
const SEALS_URL = "/sys/emapflow/modules/elecseal/queryMySeals.do",
      SIGNATRUE_SAVE = "/sys/emapflow/elecseal/submitElecSignMobile.do"

export default {
  name: 'mb-audit-comment',
  data() {
    return {
      comment: '',
      placeholder: '请输入意见',
      chapterUrl: '',
      chapterWID: '',
      chapterPopup: false,
      active: "",
      commentOpt: {},
      approval: null,
      approval_display: '',
      confirmText: '确定',
      seals: [],
      signaturePad: null,
      canvas: null,
      clearText: '清空',
      editText: '编辑签名',
      useText: '使用该签名',
      esignatureData: null,
      esignatureEdit: false,
      maxlength: 200,
      autosize: { maxHeight: 100, minHeight: 80 }
    }
  },
  props: {
    options: Object
  },
  watch: {
    approval: function(newval) {
      let option = this.commentOpt.options.filter((opt)=>{ return opt.id === newval})[0];
      this.approval_display = option.name;
      // this.placeholder = option.placeholder || this.commentOpt.tip || "请输入意见";
      // 注： 表单设计器中根据nextNode 是否为真来判断是是否需要更新下一步
      if(this.commentOpt.nextNode) {
        let emitObj = {};
        emitObj[this.options.name] = newval;
        this.$emit('formdataChange', this.options.name, emitObj, this.options)
      }      
    }
  },
  computed: {
    commentObj() {
      return {
        approval: this.approval,
        approval_display: this.approval_display,
        comment: this.comment,
        elecseal: this.chapterWID
      }
    }
  },
  methods: {
    init() {
      if(!this.options.options) return
      this.commentOpt = this.options.options;
      this.approval = this.commentOpt.defaultValue;
      this.placeholder = this.commentOpt.tip || this.placeholder;
    },
    chapterSelect() {
      if(this.chapterUrl) return;
      this.chapterPopup = true;
      const _this = this;
      this.seals = [];
      request(SEALS_URL, {
          query: {
            pageNumber: 1,
            pageSize: 10
          },
        }).then(res => {
          if(res.code !== "0") {
            _this.$notify({ type: 'danger', message: '获取印章信息失败' });
            return
          }
          res.datas.queryMySeals.rows.forEach(function(row) {
            if(row.STYPE === "0") {
              _this.seals.push(row)
            } else {
              _this.esignatureEdit = true;
              _this.esignatureData = window.contextPath + '/sys/emapflow/elecseal/loadSeal.do?wid=' + row.WID + "&_=" + new Date().getTime();
            }
          });
          _this.seals.map(function(seal){
            if(seal.WID === _this.chapterWID) {
              seal.checked = true;
            }else{
              seal.checked = false;
            }
            seal.url = window.contextPath + "/sys/emapflow/elecseal/loadSeal.do?wid=" + seal.WID;
            return seal;
          })
        })
    },
    chapterDelete() {
      this.chapterUrl = '';
      this.chapterWID = '';
    },
    tabChange(name) {
      if(name === 'esignature'){
        this.esignatureEdit = this.esignatureData ? true : false;
        if(this.esignatureData) {
          this.esignatureEdit = true;
        } else {
          this.esignatureEdit = false;
          this.initCanvas();
        }
      }
    },
    sealsChange(item) {
      this.seals = this.seals.map((seal)=>{
        seal.checked = false;
        if(seal.WID === item.WID) seal.checked = true;
        return seal
      })
    },
    elecsealConfirm() {
      let url = this.seals.filter(seal => {
        return seal.checked
      });
      if(url && url.length) {
        this.chapterUrl = url[0].url;
        this.chapterWID = url[0].WID;
      }
      this.chapterPopup = false;
    },
    initCanvas() {
      this.$nextTick(function(){
        this.canvas = this.$refs.canvas;
        this.canvas.width = this.canvas.offsetWidth;
        this.canvas.height = this.canvas.offsetHeight;
        this.signaturePad = new SignaturePad(this.canvas, {
          backgroundColor: 'rgb(255, 255, 255)'
        });
        this.signaturePad.clear()
      })
    },
    clearCanvas() {
      this.signaturePad.clear();
    },
    canvasConfirm() {
      if(this.signaturePad.isEmpty()) {
        this.$toast('签名不能为空')
      } else {
        this.esignatureData = this.signaturePad.toDataURL();
        this.esignatureEdit = true;
        this.signaturePad.clear();
      }
    },
    editCanvas() {
      this.esignatureEdit = false;
      this.initCanvas();
    },
    useCanvas() {
      if(this.esignatureData.indexOf("data:image/png;base64") !== 0) {
        this.chapterUrl = this.esignatureData;
        this.chapterWID = this.chapterUrl.match(/wid=(\S*)&/)[1];
        this.chapterPopup = false;
        return
      }
      const _this = this;
      request(SIGNATRUE_SAVE, {
        method: "POST",
        data: serialize({
          "elecSignData": this.esignatureData
        }),
        headers: {
          "content-type": "application/x-www-form-urlencoded"
        }
      }).then(function(res) {
        if(res && res.code === "0" && res.datas && res.datas.submitElecSignMobile === 1) {
          _this.$toast.success("签名创建成功");
          _this.chapterUrl = window.contextPath + '/sys/emapflow/elecseal/loadSeal.do?wid=' + res.datas.WID + "&_=" + new Date().getTime();
          _this.chapterWID = res.datas.WID;
          _this.chapterPopup = false;
        }else{
          _this.$toast.fail("签名创建失败");
        }
      });
    },
    /**
     * 校验
     */
    validate() {
      if(this.commentOpt.optionsRequired && !this.approval) {
        this.$toast.fail('审批意见选项必选')
        return false
      }
      if(this.commentOpt.required) {
        if(this.commentOpt.options && this.commentOpt.options.length && this.approval) {
          let option = this.commentOpt.options.filter((opt)=>{ return opt.id === this.approval})[0];
          if(!this.comment && option.needComment) {
            this.$toast.fail('请输入意见内容');
            return false
          }
        } else {
          if(!this.comment) {
            this.$toast.fail('请输入意见内容');
            return false
          }
        }
      }
      if(this.commentOpt.needElecseal && !this.chapterWID) {
        this.$toast.fail('请选择电子印章');
        return false
      }
      if(this.commentOpt.needEsignature && !this.chapterWID) {
        this.$toast.fail('请选择电子签名');
        return false
      }
      return true
    },
  },
  mounted() {
    this.init()
  }
}
</script>
<style scoped>
.mb-audit-comment {
  overflow: hidden;
}
.comment-title {
  padding: 12px 16px 8px 16px;
  font-size: 14px;
  border-bottom: 1px solid #ebedf0;
}
.comment-required::before {
  position: absolute;
  left: 8px;
  color: #ee0a24;
  font-size: 14px;
  content: '*';
}
.comment-approval {
  padding: 10px 16px;
}
.comment-chapter {
  position: relative;
  display: flex;
  align-items: center;
  margin-right: 16px;
  border: 1px solid #dddee1;
  border-radius: 4px;
  height: 74px;
  width: 74px;
  margin: 12px 0 12px 17px;
}
.comment-chapter-empty::before {
  position: absolute;
  top: 37px;
  left: 26px;
  content: "";
  display: block;
  width: 20px;
  height: 1px;
  background: #dddee1;
}
.comment-chapter-empty::after {
  position: absolute;
  top: 27px;
  left: 36px;
  content: "";
  display: block;
  width: 1px;
  height: 20px;
  background: #dddee1;
}
.chapter {
  display: block;
  max-height: 100%;
  max-width: 100%;
  margin: 0 auto;
}
.chapter-delete {
  position: absolute;
  right: -10px;
  top: -10px;
  height: 20px;
  width: 20px;
  background: #ccc;
  border-radius: 50%;
  display: block;
}
.chapter-delete:before {
  position: absolute;
  content: "";
  top: 10px;
  left: 5px;
  display: block;
  width: 10px;
  height: 1px;
  background: #fff;
  transform: rotate(45deg);
}
.chapter-delete:after {
  position: absolute;
  left: 10px;
  top: 5px;
  content: "";
  display: block;
  width: 1px;
  height: 10px;
  background: #fff;
  transform: rotate(45deg);
}
.navbar .van-nav-bar__title {
  max-width: 50%;
}
.tabs-content {
  height: calc(100% - 46px);
}
.tab-panel {
  height: calc(100% - 44px);
  overflow: auto;
  padding: 10px 15px;
}
.seal-empty::after {
  content: "无印章数据";
  color: #969799;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
}
.seal-box {
  float: left;
  width: 33.33%;
  margin: 5px 0;
}
.seal {
  position: relative;
  height: 100px;
  width: 100px;
  border: 1px solid #dddee1;
  border-radius: 4px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
}
.seal img {
  display: block;
  max-height: 100%;
  max-width: 100%;
}
.seal-icon {
  position: absolute;
  top: 2px; 
  right: 2px;
  z-index: 3;
}
.seal-icon-checked {
  color: #fff;
  background-color: #1989fa;
  border-color: #1989fa;
  border-radius: 100%;
}
.seal-selected::after {
  display: block;
  content: '';
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,.5);
  position: absolute;
  z-index: 2;
}
.esignatrue-box {
  position: relative;
  width: 100%;
  height: 100%;
  border: 1px solid #dddee1;
  box-shadow: 0 1px 4px rgba(0, 0, 0, .27), 0 0 40px rgba(0, 0, 0, .08) inset;
}
.esignatrue-box:after {
  content: "请在画板区域用手写下签名";
  color: #969799;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 2;
}
canvas {
  position: absolute;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  border-radius: 4px;
  box-shadow: 0 0 5px rgba(0, 0, 0, 0.02) inset;
}

</style>